import { useUserStore } from './../stores/user'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/Home/index.vue'),
      redirect: '/identify',
      children: [
        {
          path: 'identify',
          name: 'identify',
          component: () => import('../views/Identify/index.vue'),
        },
        {
          path: 'kind',
          name: 'kind',
          component: () => import('../views/Kind/index.vue'),
        },
        {
          path: 'my',
          name: 'my',
          component: () => import('../views/My/index.vue'),
        },
      ],
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login/index.vue'),
    },
    {
      path: '/kind/:id',
      name: 'detail',
      component: () => import('../views/Kind/Detail/index.vue'),
    },
  ],
})

// 白名单
const whiteList: string[] = ['/login', '/identify']

// 前置路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const token = useUserStore?.token || ''
  if (!token && !whiteList.includes(to.path)) {
    next('/login')
  } else {
    next()
  }
})

export default router
